<template>
	<uni-popup ref="popup" type="center" :mask-click="false">
		<view class="gd_detail_popup">
			<!-- 弹出框头部 -->
			<view class="popup_header">
				<text class="popup_title">挂单详情</text>
				<text @click="closePopup" class="close_btn">×</text>
			</view>

			<!-- 搜索区域 -->
			<view class="search_content">
				<view class="item_search">
					<text class="title">订单日期:</text>
					<ruiDatePicker 
						fields="day" 
						style="flex: 1; border: 1rpx solid #ccc; height: 60rpx; width: 209rpx;"
						start="2018-01-01" 
						end="2040-12-30" 
						:value="dates" 
						@change="bindChange1">
					</ruiDatePicker>
					<text>—</text>
					<ruiDatePicker 
						fields="day" 
						style="flex: 1;border: 1rpx solid #ccc; height: 60rpx; width: 209rpx;"
						start="2018-01-01" 
						end="2040-12-30" 
						:value="datee" 
						@change="bindChange2">
					</ruiDatePicker>
				</view>
				<view class="item_search" style="margin: 0 20rpx;">
					<text class="title">客户名称:</text>
					<customDownSearch
						style="flex: 1; height: 30rpx; border: 1rpx solid #ccc; font-size: 30rpx;"
						:options="KehuListCom"
						:value="form.kehuName"
						v-model="form.kehuName"
						@changeInput="changeInput1"
						@input="handleInput1"
					></customDownSearch>
				</view>

				<view class="item_search">
					<text class="title">经 手 人:</text>
					<customDownSearch
						style="flex: 1; height: 30rpx; border: 1rpx solid #ccc;font-size: 30rpx;"
						:options="kdPersonListCom"
						:value="form.yewuyuan"
						v-model="form.yewuyuan"
						@changeInput="changeInput3"
						@input="handleInput3"
					></customDownSearch>
				</view>
			</view>

			<!-- 查询按钮 -->
			<view class="search_btn">
				<!-- <u-button @click="handleDelete">删除</u-button> -->
				<u-button @click="handleSearch">查询</u-button>
			</view>

			<!-- 表格内容 -->
			<view class="table_content">
				<t-table style="width: 100%;">
					<t-tr style="position: sticky; top: 0; width: 100%; background: #fff; z-index: 9; " >
						<t-th style="flex:0 0 80upx;word-break: break-all;">
							<!-- <checkbox-group @change="changeAll">
								<checkbox value="selectAll" :checked="selectAll" />
							</checkbox-group> -->
                            /
						</t-th>
						<t-th style="flex:0 0 220upx;">订单日期</t-th>
						<t-th style="flex:0 0 151upx;">编号</t-th>
						<t-th>客户名称</t-th>
						<t-th>订单款数</t-th>
						<t-th>订单总数</t-th>
						<t-th>订单金额</t-th>
						<t-th>经手人</t-th>
					</t-tr>
					<view style="flex: 1; overflow: auto;" v-for="(item, index) in data" :key="index" @click="handleEnter(item)">
						<t-tr>
							<t-td style="flex:0 0 80upx;word-break: break-all;">
								<checkbox-group @click.stop="changeBox(item)">
									<checkbox value="check" :checked="item.check" />
								</checkbox-group>
							</t-td>
							<t-td style="flex:0 0 220upx;">{{ item.date }}</t-td>
							<t-td style="flex:0 0 151upx;">
								<view style="word-wrap: break-word; width: 151upx;">{{ item.customer_no}}</view>
							</t-td>
							<t-td>{{ item.customer_name }}</t-td>
							<t-td>{{ item.skus }}</t-td>
							<t-td>{{ item.total }}</t-td>
							<t-td>{{ item.amount }}</t-td>
							<t-td>{{ item.bizman_name }}</t-td>
						</t-tr>
					</view>

					<t-tr class="none">
						<t-th class="none" style="flex:0 0 80upx;word-break: break-all;">合计:</t-th>
						<t-th style="flex:0 0 220upx;" class="none"></t-th>
						<t-th style="flex:0 0 151upx;" class="none"></t-th>
						<t-th class="none"></t-th>
						<t-th class="none" style="color: red;">{{ sumCom }}</t-th>
						<t-th class="none" style="color: red;">{{ sumAllCom }}</t-th>
						<t-th class="none" style="color: red;">{{ amountCom.toFixed(2) }}</t-th>
						<t-th class="none"></t-th>
					</t-tr>
				</t-table>
			</view>

			<!-- 分页 -->
			<view class="bottom_content">
				<view>
					<myPagination 
						:key="'gdDetailTable-' + pageIndex"
						style="height: 80rpx;"
						:totalPage="totalCount" 
						:pageIndex="pageIndex" 
						:changeCallback="parentCallback">
					</myPagination>
				</view>
			</view>

			<!-- 底部按钮 -->
			<view class="popup_footer">
				<u-button @click="handleCancel" type="default">取消</u-button>
				<u-button @click="handleConfirm" type="primary">确认</u-button>
			</view>
		</view>
	</uni-popup>
</template>

<script>
import { mapState } from 'vuex'
import ruiDatePicker from '@/components/rattenking-dtpicker/rattenking-dtpicker.vue'
import customDownSearch from '@/components/custom-downSearch/custom-downSearch.vue'
import myPagination from '@/components/my-pagination/my-pagination.vue'
import tTable from '@/components/t-table/t-table.vue'
import tTh from '@/components/t-table/t-th.vue'
import tTr from '@/components/t-table/t-tr.vue'
import tTd from '@/components/t-table/t-td.vue'

import { query_gorders, dingdState, delete_gorders } from "@/api/modules/table.js"
import { getKehuList, getKdPersonList } from '@/api/modules/select.js'

const { currentdate, beforedate } = getNowFormatDate()
var timer_s = beforedate
var timer_e = currentdate
function getNowFormatDate() {
	var date = new Date();
	var seperator1 = "-";
	var month = date.getMonth() + 1;  // 当前月
	var month2 = month - 2;  // 当前月往前推2个月
	var strDate = date.getDate();  // 当前日
	
	// 如果月份小于10，前面加0
	if (month >= 1 && month <= 9) {
		month = "0" + month;
	}
	
	// 如果月份2小于10，前面加0
	if (month2 < 1) {
		month2 += 12;  // 如果月份为负数，回到上一年
		date.setFullYear(date.getFullYear() - 1);  // 年份减1
	}
	if (month2 >= 1 && month2 <= 9) {
		month2 = "0" + month2;
	}

	// 如果日期小于10，前面加0
	if (strDate >= 1 && strDate <= 9) {
		strDate = "0" + strDate;
	}

	var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;
	var beforedate = date.getFullYear() + seperator1 + month2 + seperator1 + strDate;
	return {
		currentdate,
		beforedate
	};
}

function debounce(func, wait) {  
	let timeout;  
	return function() {  
		const context = this;  
		const args = arguments;  
		if (timeout) clearTimeout(timeout);  
		timeout = setTimeout(function() {  
		func.apply(context, args);  
		}, wait);  
	};  
}

export default {
	name: 'GdDetailTable',
	components: {
		ruiDatePicker,
		customDownSearch,
		myPagination,
		tTable,
		tTh,
		tTr,
		tTd,
	},
	props: {
		active_menu_id: {
			type: String,
			default: ''
		}
	},
	data() {
		return {
			dates: timer_s,
			datee: timer_e,
			form: {
				kehuName: '', // 客户名称
				yewuyuan: '', // 业务员
			},
			selectAll: false, // 全选按钮
			data: [],

			kehuList: [], // 客户名称
			yewuSelectList: [], // 业务员
			pageSize: 10, // 下单页数
			pageIndex: 1, // 当前页数
			totalCount: 0, // 应该有多少条数据

			debouncedGetKehu: debounce(this.getKehu, 500),  // 客户名称 防抖
			debouncedKdPerson: debounce(this.getKdPerson, 500),  // 开单业务 防抖
		}
	},
	computed: {
		KehuListCom(){
			let arr = [];
			(this.kehuList || []).forEach(i => {
				arr.push(i.name)
			})
			return arr
		},
		kdPersonListCom(){
			let arr = [];
			(this.yewuSelectList || []).forEach(i => {
				arr.push(i.name)
			})
			return arr
		},
		sumCom() {
			return this.data.reduce((a, b) => a += b.skus, 0)
		},
		sumAllCom() {
			return this.data.reduce((a, b) => a += b.total, 0)
		},
		amountCom() {
			let sumA = this.data.reduce((a, b) => a + parseInt(b.amount * 10000), 0)
			return sumA / 10000
		},
	},
	watch: {
		data: {
			handler(newVal, oldVal) {
				if (newVal.length == 0) {
					this.selectAll = false
					return
				}
				if (newVal.every(i => i.check)) {
					this.selectAll = true
				} else {
					this.selectAll = false
				}
			},
			immediate: true,
			deep: true
		}
	},
	mounted() {
		this.initData()
	},
	methods: {
		initData() {
			let param = {
				paging: {
					pageIndex: 1,
					pageSize: this.pageSize,
				}, 
				query: {
					state: '', // 订单状态
					customer_id: '', // 客户订单
					bizman_id: '', // 业务员
					active_menu_id: this.active_menu_id, // 菜单id
					startdate: this.dates, 
					enddate: this.datee,
					search: '', //查询指定产品订单
				}
			}
			this._tableDetail(param);
			this.getKehu(); // 客户名称
			this.getKdPerson(); // 开单业务员
		},
		
		// 打开弹出框
		openPopup() {
			this.$refs.popup.open();
		},
		
		// 关闭弹出框
		closePopup() {
			this.$refs.popup.close();
		},
		
		// 取消按钮
		handleCancel() {
			this.closePopup();
			this.$emit('cancel');
		},
		
		// 确认按钮
		handleConfirm() {
			const selectedItems = this.data.filter(item => item.check);
			this.closePopup();
			this.$emit('confirm', selectedItems);
		},
		
		parentCallback(pages) {
			this.pageIndex = pages
			let param = {
				paging: {
					pageIndex: pages,
					pageSize: this.pageSize,
				}, 
				query: {
					customer_id: this.kehuList.filter(i => i.name == this.form.kehuName)[0]?.id, // 客户订单
					bizman_id: this.yewuSelectList.filter(i => i.name == this.form.yewuyuan)[0]?.id, // 业务员
					startdate: this.dates, 
					enddate: this.datee,
					search: '', //查询指定产品订单
					active_menu_id: this.active_menu_id, // 菜单id
				}
			}
			this._tableDetail(param);
		},
		
		handleSearch() {
			let param = {
				paging: {
					pageIndex: 1,
					pageSize: this.pageSize,
				}, 
				query: {
					customer_id: this.kehuList.filter(i => i.name == this.form.kehuName)[0]?.id, // 客户订单
					bizman_id: this.yewuSelectList.filter(i => i.name == this.form.yewuyuan)[0]?.id, // 业务员
					startdate: this.dates, 
					enddate: this.datee,
					search: '', //查询指定产品订单
					active_menu_id: this.active_menu_id, // 菜单id
				}
			}

			this.pageIndex = 1
			this._tableDetail(param);
		},
		
		async handleDelete() {
			if (!this.data.filter(i => i.check).length ) {
				uni.showToast({
					title: '请选择要删除的订单!',
					duration: 2000,
					icon: 'none'
				});
				return
			}
			let param = JSON.parse(JSON.stringify(this.data)).filter(i => i.check).map(i => ({id: i.id, no: i.no}))
			const res = await delete_gorders(JSON.stringify(param))
			const { data: { status, message } } = res || {}

			if (status == 'success') {
				uni.showToast({
					title: '删除成功!',
					duration: 2000,
					icon: 'none'
				});
				this.data = JSON.parse(JSON.stringify(this.data)).filter(i => !i.check)
			} else if (status === 'fail') {
				uni.showToast({
					title: message,
					duration: 2000,
					icon: 'none'
				});
			} 
		},
		
		changeAll() { // 全选
			this.selectAll = !this.selectAll
			if (this.selectAll) {
				this.data = JSON.parse(JSON.stringify(this.data)).map((i, j) => ({...i, check: true}))
			} else if (!this.selectAll) {
				this.data = JSON.parse(JSON.stringify(this.data)).map((i, j) => ({...i, check: false}))
			}
		},
		
		changeBox(item) { // 单选
			// this.data = JSON.parse(JSON.stringify(this.data)).map((i, j) => ({...i, check: j === index ? !i.check : i.check}))
			// e.stopPropagation()
			// e.preventDefault()

            this.data = this.data.map((i, j) => ({...i, check: i.id === item.id ? !i.check : false}))
		},
		
		handleEnter(param) {
			console.log('== 选择订单', param)
			// 可以在这里处理订单选择逻辑
		},
		
		changeInput1(opt) {
			this.form.kehuName = opt
		},
		handleInput1(opt) {
			this.form.kehuName = opt
			this.debouncedGetKehu(opt)
		},

		changeInput3(opt) {
			this.form.yewuyuan = opt
		},
		handleInput3(opt) {
			this.form.yewuyuan = opt
			this.debouncedKdPerson(opt)
		},

		bindChange1(value) { // 日期选择
			this.dates = value;
		},
		bindChange2(value) { // 日期选择
			this.datee = value;
		},
		
		async _tableDetail(param) {
			const res = await query_gorders(JSON.stringify(param))
			const { data: { data, status, message } } = res || {}

			if (status == 'success') {
				if (!data.gorders.length) {
					uni.showToast({
						title: '暂无数据!',
						duration: 2000,
						icon: 'none'
					});
				}
				this.totalCount = Math.ceil(data.paging.total / this.pageSize)
				this.data = (data.gorders || []).map(i => ({ 
					...i, 
					check: false, 
				}))
			} else if (status === 'fail') {
				uni.showToast({
					title: message,
					duration: 2000,
					icon: 'none'
				});
			} 
		},
		
		async getKehu(str='') { // 客户信息
			let param = {
				paging: {
					pageIndex: 1,
					pageSize: 200,
				},
				query: {
					type_nos: ["customer"],
					valid: true,
					search: str, // 搜索字段
				},
			}
			const res = await getKehuList(JSON.stringify(param))
			const { data: { data } } = res || {}
			this.kehuList = (data.companys ? data.companys : [])
		},

		async getKdPerson(str = '') { // 开单业务
			let param = {
				paging: {
					pageIndex: 1,
					pageSize: 200,
				},
				query: {
					role_type_no: "wms",
					refcompany: false,
					valid: true,
					search: str, // 搜索字段
				},
			}
			const res = await getKdPersonList(JSON.stringify(param))
			const { data: { data } } = res || {}
			this.yewuSelectList = (data.users ? data.users : [])
		},
	}
}
</script>

<style lang="less" scoped>
.gd_detail_popup {
	width: 90vw;
	height: 80vh;
	background: #fff;
	border-radius: 20rpx;
	display: flex;
	flex-direction: column;
	overflow: hidden;
	
	.popup_header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		background: #f8f9fa;
		border-bottom: 1rpx solid #e5e5e5;
		
		.popup_title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
		}
		
		.close_btn {
			font-size: 40rpx;
			color: #999;
			cursor: pointer;
			padding: 10rpx;
			
			&:hover {
				color: #666;
			}
		}
	}
	
	.search_content {
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx;
		border-bottom: 1rpx solid #e5e5e5;
		
		.item_search {
			display: flex;
			align-items: center;
			height: 60rpx;
			width: 33%;
			margin-right: 20rpx;

			.title {
				font-size: 28rpx;
				font-weight: 700;
				width: 120rpx;
                white-space: nowrap;
			}
		}
	}

	.search_btn {
		display: flex;
		justify-content: space-between;
		justify-content: flex-end;
		padding: 20rpx 30rpx;
		border-bottom: 1rpx solid #e5e5e5;

		button {
			width: 200rpx;
			color: #fff;
			margin: 0;
			font-size: 28rpx;
		}

		// button:nth-child(1) {
		// 	background: red;
		// }
		button:nth-child(1) {
			background: #f59a23;
		}
	}
	
	.table_content {
		flex: 1;
		overflow: auto;
		padding: 0 30rpx;
	}

	.bottom_content {
		padding: 20rpx 30rpx;
		border-top: 1rpx solid #e5e5e5;
		font-size: 28rpx;
	}
	
	.popup_footer {
		display: flex;
		justify-content: space-around;
		padding: 30rpx;
		border-top: 1rpx solid #e5e5e5;
		gap: 20rpx;
		
		button {
			flex: 1;
			height: 80rpx;
			font-size: 32rpx;
		}
	}
}

.none {
	border: none;
}
</style>
